package com.lzh.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lzh.auto.TokenProperties;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TokenTemplate {

    TokenProperties properties;//存储配置信息 密钥 有效期...

    public TokenTemplate(TokenProperties tokenProperties) {
        this.properties = tokenProperties;
    }

    /**
     * 生成token
     *
     * @param payload
     * @return
     */
    public String generateToken(Map payload) {
        String token = JWT.create()
                .withHeader(getHeader()) //头部
                .withPayload(payload)
                .withIssuer("by")
                .withExpiresAt(getExpireDate())
                .sign(Algorithm.HMAC256(properties.getSecret()));
        return token;
    }


    public ValidResult valid(String token) {
        //验证token
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(properties.getSecret()))
                .build();
        DecodedJWT decodedJWT = null;
        try {
            decodedJWT = verifier.verify(token);
        } catch (JWTDecodeException e) {
            return new ValidResult(1, "token无效", null);
        } catch (TokenExpiredException e) {
            return new ValidResult(2, "token过期", null);
        }
        Map<String, Claim> payload = decodedJWT.getClaims();
        Map<String, Object> tmp = new HashMap<>();
        tmp.put("id", payload.get("id").asInt());
        tmp.put("username", payload.get("username").asString());
        tmp.put("type", payload.get("type").asInt());
        return new ValidResult(3, "有效", tmp);
    }

    Date getExpireDate() {
        //获取30分钟后日期
        Date date = new Date(System.currentTimeMillis() + properties.getValidTime());
        return date;
    }


    Map getHeader() {
        Map<String, String> map = new HashMap<>();
        map.put("typ", "JWT");
        map.put("alg", "HMAC256");
        return map;
    }
}
